/* eslint-disable */
/**
 * 格式化时间
 */
const formatTime = timestamp => {
    const seconds = parseInt(timestamp / 1000, 10);

    const s = parseInt(seconds % 60, 10);
    const m = parseInt((seconds / 60) % 60, 10);
    const h = parseInt((seconds / 3600) % 24, 10);

    const ary = [];
    ary.push(h < 10 ? `0${h}` : h);
    ary.push(m < 10 ? `0${m}` : m);
    ary.push(s < 10 ? `0${s}` : s);

    return ary.join(':');
};

/**
 * 将二进制数组转换为File对象，类型为mp3
 * @param {ArrayBuffer} binaryArr
 * @returns
 */
const arrayBufferToMp3File = binaryArr => new File(binaryArr, `${+new Date()}.mp3`, { type: 'audio/mpeg' });

/**
 * blob 数组转换为 Uint8Array 数组
 * @param {[Blob]} blobArr
 * @returns Promise
 */
const blobToUint8Array = blobArr =>
    new Promise((resolve, reject) => {
        const promiseArr = [];
        for (const blob of blobArr) {
            promiseArr.push(
                new Promise(resolve => {
                    const reader = new FileReader();
                    reader.onloadend = function() {
                        resolve(new Uint8Array(reader.result));
                    };
                    reader.readAsArrayBuffer(blob);
                })
            );
        }
        Promise.all(promiseArr).then(
            resArr => {
                resolve(resArr);
            },
            e => {
                console.error(e);
                reject(e);
            }
        );
    });

/**
 * ArrayBuffer 转 File 并下载
 * @param {ArrayBuffer} arrayBuffer
 */
const saveArrayBufferAsFile = arrayBuffer => {
    const file = arrayBufferToMp3File(arrayBuffer);
    const fileUrl = window.URL.createObjectURL(file);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.download = `concat-${+new Date()}.mp3`;
    a.href = fileUrl;
    a.click();
    window.URL.revokeObjectURL(fileUrl);
};

/**
 * 处理合并后 mp3 文件
 */
const afterConcat = (file, duration, info) => {
    console.log(file);
    console.log(duration);
    console.log(info);
    saveArrayBufferAsFile([file.buffer]);
};

/**
 * 判断传入字符串中是否包含https://
 * @param {string} url
 */
const isHttps = (url = '') => {
    return url.includes('https://');
};

export { isHttps, formatTime, arrayBufferToMp3File, blobToUint8Array, saveArrayBufferAsFile, afterConcat };
